package com.mingyizhudao.app.view.booking;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.CompoundButton.OnCheckedChangeListener;

import com.dixiang.framework.common.QJNetUICallback2;
import com.dixiang.framework.common.QjResult;
import com.dixiang.framework.config.SystemConfig;
import com.dixiang.framework.network2.NetOld;
import com.dixiang.framework.utils.AlertDialogs;
import com.dixiang.framework.utils.BitmapCache;
import com.dixiang.framework.utils.Utils;
import com.dixiang.framework.widget.LoadingDialog;
import com.google.gson.reflect.TypeToken;
import com.mingyizhudao.app.R;
import com.mingyizhudao.app.moudle.bitmap.BimpTempHelper;
import com.mingyizhudao.app.moudle.bitmap.ImageGridActivity;
import com.mingyizhudao.app.moudle.bitmap.ImageItem;
import com.mingyizhudao.app.moudle.bitmap.NoScrollGridView;
import com.mingyizhudao.app.moudle.bitmap.PhotoActivity;
import com.mingyizhudao.app.utils.CommonUtils;
import com.mingyizhudao.app.utils.Constants;
import com.mingyizhudao.app.utils.IntentHelper;
import com.mingyizhudao.app.utils.ToastUtil;
import com.mingyizhudao.app.utils.UploadUtils;
import com.mingyizhudao.app.utils.UploadUtils.OnLoadListener;
import com.mingyizhudao.app.view.MYApplication;
import com.mingyizhudao.app.view.MYBaseActivity;
import com.mingyizhudao.app.view.PayViewActivity;
import com.mingyizhudao.app.view.WebViewActivity;
import com.mingyizhudao.app.view.mine.OrderListActivity;

public class FastBookingActivity extends MYBaseActivity{
	private NoScrollGridView noScrollgridview;
	private GridAdapter adapter;
	private BitmapCache cache;
	private List<ImageItem> dataChoosed = new ArrayList<ImageItem>();// 选中的item
	private Handler handler = new Handler();

	private String bookingId;
	private static final int FAIL = 500;// 更新下载进度的标记
	private static final int SUCCESS = 200;
	private ProgressDialog progressDialog;
	private String payUrl;

	private EditText et_hp,et_dpt,et_dt_name,et_p_name,et_phone,et_syscode,et_disease,et_dsc;
	private View get_code;
	private TextView btn_getsmscode;
	private Button btn_commit;
	private boolean hasLogin = false;
	private TimeCount timeCount;

	private LinearLayout ll_content;
	private ImageView iv_go_down;
	
	private CheckBox cb_agree;
	private TextView tv_agreement;
	@Override
	public void initHeaderView() {
		setTopViewBg(R.color.actionbar_bg_color);
		initBackView(R.drawable.left_back_white_icon, 0, new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		setTitleViewValue(0, 0, R.color.white);
		setTitleViewValue("快速预约");
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_fast_booking);
		initView();
	}

	private void initView(){

		progressDialog = new ProgressDialog(this);
		progressDialog.setCanceledOnTouchOutside(false);
		progressDialog.setMessage("上传中...");

		noScrollgridview = (NoScrollGridView) findViewById(R.id.noScrollgridview);
		noScrollgridview.setSelector(new ColorDrawable(Color.TRANSPARENT));
		cache = new BitmapCache(this, Constants.PHOTOWIDTH);

		adapter = new GridAdapter(this);
		noScrollgridview.setAdapter(adapter);
		noScrollgridview
		.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				if (arg2 == dataChoosed.size()) {

					// IntentHelper.getInstance(activity).gotoActivity(ImageGridActivity.class,
					// null, 1011);
					Intent intent = new Intent(activity,
							ImageGridActivity.class);
					startActivityForResult(intent, 1011);
					// intent.putExtra("isDymic", true);
					// startActivity(intent);
				} else {
					Intent intent = new Intent(activity,
							PhotoActivity.class);
					intent.putExtra("ID", arg2);
					startActivityForResult(intent, 1012);
				}
			}
		});


		et_hp = (EditText) findViewById(R.id.et_hp);
		et_dpt = (EditText) findViewById(R.id.et_dpt);
		et_dt_name = (EditText) findViewById(R.id.et_dt_name);
		et_p_name = (EditText) findViewById(R.id.et_p_name);
		et_phone = (EditText) findViewById(R.id.et_phone);
		et_syscode = (EditText) findViewById(R.id.et_syscode);
		et_disease = (EditText) findViewById(R.id.et_disease);
		et_dsc = (EditText) findViewById(R.id.et_dsc);

		get_code = findViewById(R.id.get_code);

		btn_commit = (Button) findViewById(R.id.btn_commit);

		btn_getsmscode = (TextView) findViewById(R.id.btn_getsmscode);

		btn_getsmscode.setOnClickListener(onClickListener);

		String token = CommonUtils.getToken(this);
		if(token!=null&&token.length()>0&&!"null".equals(token)){
			hasLogin = true;
			get_code.setVisibility(View.GONE);
		}
		timeCount = new TimeCount(60000, 1000);// 构造CountDownTimer对象



		ll_content = (LinearLayout) findViewById(R.id.ll_content);
		final int offset= (int) (MYApplication.heightPixels-MYApplication.startheight - 43* MYApplication.density);
		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, offset);
		ll_content.setLayoutParams(params);

		final SlowScrollView scrollview_parent = (SlowScrollView) findViewById(R.id.scrollview_parent);
		iv_go_down = (ImageView) findViewById(R.id.iv_go_down);

		iv_go_down.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				scrollview_parent.smoothScrollToSlow(0, offset, 1500);
			}
		});
		

		

		cb_agree = (CheckBox) findViewById(R.id.cb_agree);
		tv_agreement = (TextView) findViewById(R.id.tv_agreement);
		tv_agreement.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Bundle bundle = new Bundle();
				bundle.putString(Constants.PARM_ACTION_URL, "http://m.mingyizhudao.com/mobile/user/index/page/aboutAgreement/header/0");
				bundle.putString(Constants.PARM_PAGE_TITLE, "名医主刀服务协议");
				
				IntentHelper.getInstance(activity).gotoActivity(WebViewActivity.class, bundle);
			}
		});
		
		
		if (!cb_agree.isChecked()) {
			btn_commit.setBackgroundDrawable(getResources().getDrawable(R.drawable.button_can_not));
			btn_commit.setClickable(false);
		}
		cb_agree.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				if (isChecked) {
					btn_commit.setBackgroundDrawable(getResources().getDrawable(R.drawable.button_gold_cyan_bg));
					btn_commit.setClickable(true);
				}else {
					btn_commit.setBackgroundDrawable(getResources().getDrawable(R.drawable.button_can_not));
					btn_commit.setClickable(false);
				}
				
			}
		});
	}


	public static void scrollToBottom(final View scroll, final View inner) {

		Handler mHandler = new Handler();

		mHandler.post(new Runnable() {
			public void run() {
				if (scroll == null || inner == null) {
					return;
				}
				int offset = inner.getMeasuredHeight() - scroll.getHeight();
				if (offset < 0) {
					offset = 0;
				}

				scroll.scrollTo(0, offset);
			}
		});
	}
	public void onBooking(View view){
		checkData();
	}

	private void checkData(){
		String hp_name = et_hp.getText().toString().trim();
		String dpt_name = et_dpt.getText().toString().trim();
		String dct_name = et_dt_name.getText().toString().trim();
		String p_name = et_p_name.getText().toString().trim();
		String phone = et_phone.getText().toString().trim();
		String sysCode = et_syscode.getText().toString().trim();
		String disease = et_disease.getText().toString().trim();
		String dsc = et_dsc.getText().toString().trim();

		final Map map = new HashMap<String,Object>();
		map.put("hospital_name", hp_name);
		map.put("hp_dept_name", dpt_name);
		map.put("doctor_name", dct_name);

		if(Utils.isStringEmpty(p_name)){
			et_p_name.requestFocus();
			ToastUtil.showToast(this, "填写患者姓名");
			return;
		}
		if(p_name.length()>10){
			et_p_name.requestFocus();
			ToastUtil.showToast(this, "患者姓名不超过10个字！");
			return;
		}
		
		//		if(Utils.isStringEmpty(disease)){
		//			et_disease.requestFocus();
		//			ToastUtil.showToast(this, "请填写确诊疾病");
		//			return;
		//		}


		if(Utils.isStringEmpty(dsc)){
			et_dsc.requestFocus();
			ToastUtil.showToast(this, "请填写病情描述");
			return;
		}

		if(dsc.length()<10){
			et_dsc.requestFocus();
			ToastUtil.showToast(this, "病情描述至少10字！");
			return;
		}

		if(hasLogin){
			map.put("username", CommonUtils.getMobile(activity));
			map.put("token", CommonUtils.getToken(activity));
		}else{
			if(!Utils.checkMobile(phone)){
				et_phone.requestFocus();
				ToastUtil.showToast(this, "请核对您的手机号码！");
				return;
			}
			if(Utils.isStringEmpty(sysCode)){
				et_syscode.requestFocus();
				ToastUtil.showToast(this, "请输入验证码");
				return;
			}
			map.put("mobile", phone);
			map.put("verify_code", sysCode);
		}

		map.put("contact_name", p_name);
		map.put("disease_name", disease);
		map.put("disease_detail", dsc);
		map.put("key", "booking");
	
		final String url = getIntent().getStringExtra(Constants.PARM_ACTION_URL);
		if (dataChoosed != null && dataChoosed.size() > 0) {
			AlertDialogs dlg = AlertDialogs.getAlertDialog(activity);
			dlg.setOk( "提交" );
			dlg.showAlertDialog(
					"您已经选中了" + dataChoosed.size() + "张影像资料,确认提交！",
					new OnClickListener() {
						@Override
						public void onClick(View arg0) {
							LoadingDialog.getInstance(activity).show();
							btn_commit.setEnabled(false);
							postHttpResult(url, map, Constants.HTTP_INDEX.First, new TypeToken<QjResult<Map<String, Object>>>() {});
						}
					});
		} else {
			AlertDialogs dlg = AlertDialogs.getAlertDialog(activity);
			dlg.setOk( "提交" );
			dlg.setContent2(true, "（可以在预约单详情界面添加）" );
			dlg.showAlertDialog(
					"您尚未上传影像资料,确认提交？",
					new OnClickListener() {
						@Override
						public void onClick(View arg0) {
							LoadingDialog.getInstance(activity).show();	
							btn_commit.setEnabled(false);
							postHttpResult(url, map, Constants.HTTP_INDEX.First, new TypeToken<QjResult<Map<String, Object>>>() {});
						}
					});
		}

	}

	public void onSendSysCode(){
		String phone = et_phone.getText().toString().trim();
		if(Utils.checkMobile(phone)){
			timeCount.start();// 开始计时
			Map params = new HashMap<String , Object>();
			params.put("mobile", phone);
			params.put("action_type", 200);
			params.put("key", "smsVerifyCode");
			String url = CommonUtils.getSendCodeUrl(activity);
			postHttpResult(url, params, Constants.HTTP_INDEX.Second, new TypeToken<QjResult<Map<String, Object>>>() {});
			return;
		}
		et_phone.requestFocus();
		ToastUtil.showToast(this, "请核对您的手机号码！");
	}

	@Override
	public void onSuccess(QjResult result, String flg) {
		super.onSuccess(result, flg);
		if(flg.equals(Constants.HTTP_INDEX.First)){
			Map<String, Object> map = (Map<String, Object>)result.getResults();

			bookingId = map.get("booking_id")+"";

			String refNo = map.get("refNo")+"";
			String token = (String) map.get("token");

			if(token!=null&&token.length()>0&&!"null".equals(token)){
				CommonUtils.setToken(activity, token);
				String phone = et_phone.getText().toString().trim();
				CommonUtils.setMobile(activity, phone);
			}
			//上传到七牛的图片地址
			String fileUrl = map.get("actionUrl")+"";

			payUrl = CommonUtils.getPayUrl(activity, refNo);

			if (dataChoosed != null && dataChoosed.size() > 0) {
				upQiniu();

			} else {
				gotoResultView();
			}
		}else if(flg.equals(Constants.HTTP_INDEX.Second)){
			Toast.makeText(activity, "验证码已发送，注意查收！", 0)
			.show();
		}
	}

	@Override
	public void onFailure(QjResult result, String flg) {
		
		if(flg.equals(Constants.HTTP_INDEX.Second)){
			super.onFailure(result, flg);
//			timeCount.cancel();
//			Toast.makeText(activity, "验证码发送失败！", 0).show();
//			btn_getsmscode.setText("获取验证码");
//			btn_getsmscode.setClickable(true);
//			btn_getsmscode.setTextColor(getResources().getColor(R.color.fast_booking_btn));

			//btn_getsmscode.setBackgroundResource(R.drawable.button_border_bg);

			handler.post(new Runnable() {
				@Override
				public void run() {
					timeCount.cancel();
					Toast.makeText(activity, "验证码发送失败！", 0).show();
					btn_getsmscode.setText("获取验证码");
					btn_getsmscode.setClickable(true);
					btn_getsmscode.setTextColor(getResources().getColor(R.color.fast_booking_btn));		
				}
			});
			

		}else if (flg.equals(Constants.HTTP_INDEX.First)) {
			super.onFailure(result, flg);
			
		}
	}

	@Override
	public void onCompleted(Exception e, String flg) {
		super.onCompleted(e, flg);
		LoadingDialog.getInstance(activity).dismiss();
		handler.post(new Runnable() {
			@Override
			public void run() {
				btn_commit.setEnabled(true);				
			}
		});
		
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (requestCode==1) {
			IntentHelper.getInstance(activity).gotoActivity(OrderListActivity.class);
			finish();
		}else {
			dataChoosed = BimpTempHelper.getInstance().getImageItemsChoosend();
			noScrollgridview.setAdapter(adapter);
		}

	};

	private OnClickListener onClickListener = new OnClickListener() {

		@Override
		public void onClick(View arg0) {
			switch (arg0.getId()) {
			case R.id.btn_getsmscode:
				onSendSysCode();
				break;
			default:
				break;
			}
		}
	};

	class TimeCount extends CountDownTimer {
		public TimeCount(long millisInFuture, long countDownInterval) {
			super(millisInFuture, countDownInterval);// 参数依次为总时长,和计时的时间间隔
		}

		@Override
		public void onFinish() {// 计时完毕时触发
			btn_getsmscode.setText("获取验证码");
			btn_getsmscode.setClickable(true);
			//btn_getsmscode.setBackgroundResource(R.drawable.button_border_bg);
			btn_getsmscode.setTextColor(getResources().getColor(R.color.fast_booking_btn));
		}

		@Override
		public void onTick(long millisUntilFinished) {// 计时过程显示
			btn_getsmscode.setClickable(false);
			btn_getsmscode.setTextColor(getResources().getColor(R.color.btn_timing_gray));
			//btn_getsmscode.setBackgroundColor(getResources().getColor(R.color.btn_timing_gray));
			btn_getsmscode.setText(millisUntilFinished / 1000 + "秒后重发");
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode == KeyEvent.KEYCODE_BACK){
			AlertDialogs.getAlertDialog(activity).showAlertDialog("你确定要放弃编辑吗？", new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					finish();
				}
			});
		}
		return super.onKeyDown(keyCode, event);
	}



	public class GridAdapter extends BaseAdapter {
		private LayoutInflater inflater; // 视图容器
		private int selectedPosition = -1;// 选中的位置
		private boolean shape;

		public boolean isShape() {
			return shape;
		}

		public void setShape(boolean shape) {
			this.shape = shape;
		}

		public GridAdapter(Context context) {
			inflater = LayoutInflater.from(context);
		}

		public int getCount() {
			if (dataChoosed.size() == Constants.PHOTO_MAX_SIZE) {
				return Constants.PHOTO_MAX_SIZE;
			}
			return (dataChoosed.size() + 1);
		}

		public Object getItem(int arg0) {

			return null;
		}

		public long getItemId(int arg0) {

			return 0;
		}

		public void setSelectedPosition(int position) {
			selectedPosition = position;
		}

		public int getSelectedPosition() {
			return selectedPosition;
		}

		/**
		 * ListView Item设置
		 */
		public View getView(int position, View convertView, ViewGroup parent) {
			final int coord = position;
			ViewHolder holder = null;
			if (convertView == null) {
				convertView = inflater.inflate(R.layout.myablum_item, parent,
						false);
				holder = new ViewHolder();
				holder.image = (ImageView) convertView
						.findViewById(R.id.blum_image);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			if (position == dataChoosed.size()) {
				holder.image.setImageBitmap(BitmapFactory.decodeResource(
						getResources(), R.drawable.icon_addpic_unfocused));
				if (position == Constants.PHOTO_MAX_SIZE) {
					holder.image.setVisibility(View.GONE);
					convertView.setVisibility(View.GONE);
				}

			} else {
				cache.displayBmp(holder.image,
						dataChoosed.get(position).imagePath, handler);
			}
			return convertView;
		}

		public class ViewHolder {
			public ImageView image;
		}

	}


	private void upQiniu() {
		progressDialog.show();
		final List<File> files = new ArrayList<File>();
		for (int i = 0; i < dataChoosed.size(); i++) {
			files.add(new File(dataChoosed.get(i).imagePath));
		}

		UploadUtils uploadUtils =new UploadUtils( bookingId);

		uploadUtils.uploadFiles(activity, null, files, new OnLoadListener() {

			@Override
			public void onLoadSuccess(String remoteDomain ,String key, String str, int index) {
				doTestNet(remoteDomain ,files.get(index), index  ,key);

			}

			@Override
			public void onLoadSuccess(String remoteDomain ,String key, String str) {
				LoadingDialog.getInstance(activity).dismiss();
			}

			@Override
			public void onLoadFail() {
				progressDialog.dismiss();
				LoadingDialog.getInstance(activity).dismiss();
				Toast.makeText(activity, "上传失败！", Toast.LENGTH_LONG).show();

			}
		});

	}
	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {

			case SUCCESS:
				progressDialog.dismiss();
				Toast.makeText(activity, "上传成功！", 2000).show();
				gotoResultView();
				break;
			case FAIL:
				progressDialog.dismiss();
				Toast.makeText(activity, "上传失败！", 2000).show();
				break;
			default:
				break;
			}
		}
	};

	private void gotoResultView() {
		//			IntentHelper.getInstance(activity).gotoActivityWithURL(PayViewActivity.class, payUrl);
		Intent intent = new Intent(activity,PayViewActivity.class);
		Bundle bundle = new Bundle();
		bundle.putString(Constants.PARM_ACTION_URL, payUrl);
		bundle.putString(Constants.PARM_PAGE_TITLE, "支付");
		intent.putExtras(bundle);
		startActivityForResult(intent, 1);
	}


	//上传七牛成功数据保存至自己服务器
	@SuppressWarnings("unchecked")
	private void doTestNet(String remoteDomain ,File file ,final int index, String key) {

		Map map = new HashMap<String, Object>();

		map.put("appFile[token]", CommonUtils.getToken(activity));
		map.put("appFile[username]", CommonUtils.getMobile(activity));

		map.put("appFile[size]", file.length()/1024+"");
		if (file.getName().endsWith(".png")) {
			map.put("appFile[type]", "png");
		}else {
			map.put("appFile[type]", "jpg");
		}

		map.put("appFile[remoteDomain]", remoteDomain);
		map.put("appFile[remoteKey]", key);

		map.put("appFile[bookingId]", bookingId);



		QJNetUICallback2 callback = new QJNetUICallback2<QjResult<HashMap<String, Object>>>(activity) {
			@Override
			public void onSuccess(QjResult<HashMap<String, Object>> result) {
				if (result != null) {
					if (index+1 ==dataChoosed.size()) {
						//ToastUtil.showToast(activity, "提交自己服务器成功！",Toast.LENGTH_LONG);
						mHandler.sendEmptyMessage(SUCCESS);
					} 
				}else {
					mHandler.sendEmptyMessage(FAIL);
				}
			}

			public void onError(Exception e, QjResult<HashMap<String, Object>> result) {
				super.onError(e, result);
				ToastUtil.showToast(activity, "提交自己服务器失败！",Toast.LENGTH_LONG);
				mHandler.sendEmptyMessage(FAIL);
			}

			public void onCompleted(Exception e, QjResult<HashMap<String, Object>> result) {
				super.onCompleted(e, result);
			}
		};
		NetOld.with(activity).fetch(SystemConfig.SAVE_APP_FILE ,map, new TypeToken<QjResult<HashMap<String, Object>>>() {}, callback);
	}

	@Override
	protected void onDestroy() {
		BimpTempHelper.getInstance().clearData();
		super.onDestroy();
	}
}
